using System.Collections.Generic;
using CoreLib.ConfigOptions;
using IdentityServer4;
using IdentityServer4.Models;
using Ids.GrantValidators;
using Ids.UserServices;
using Ids.UserServices.Implements;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new() { Title = "Ids", Version = "v1" });
});

builder.Services.Configure<ApproveServiceOptions>(builder.Configuration.GetSection("ApproveService"));

#region IdentityServer

builder.Services.AddIdentityServer()
                .AddExtensionGrantValidator<LoginByService>()
                .AddDeveloperSigningCredential()
                .AddInMemoryClients(new List<Client>
                {
                    new Client
                    {
                        ClientId="mobileApprove",

                        AllowedGrantTypes= {
                            "LoginByService"
                        },
                        RefreshTokenExpiration=TokenExpiration.Sliding,
                        AllowOfflineAccess=true,
                        RequireClientSecret=false,
                        AlwaysIncludeUserClaimsInIdToken=true,
                        ClientSecrets= {
                            new Secret("secret".Sha256())
                        },
                        AccessTokenLifetime = 14400,
                        AllowedScopes= {
                            "xquant-mobile-approve-exam",
                            IdentityServerConstants.StandardScopes.OpenId,
                            IdentityServerConstants.StandardScopes.Profile
                        }
                    },
                })
                .AddInMemoryIdentityResources(new List<IdentityResource>
                {
                    new IdentityResources.OpenId(),
                    new IdentityResources.Profile()
                })
                .AddInMemoryApiResources(new List<ApiResource>
                {
                    new ApiResource("xquant-mobile-approve-exam", "xQuant Mobile Approve EXAM"){ Scopes={ "xquant-mobile-approve-exam" } },
                })
                .AddInMemoryApiScopes(new List<ApiScope>
                {
                    new ApiScope("xquant-mobile-approve-exam", "xQuant EXAM API"),
                });

builder.Services.AddScoped<IUserService, ApproveServiceLoginServer>();

#endregion

var app = builder.Build();

// Configure the HTTP request pipeline.
if (builder.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
    app.UseSwagger();
    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Ids v1"));
}

app.UseIdentityServer();

app.MapControllers();

app.Run();
